/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

#include <cassert>
#include <cstring>
#include <fstream>
#include <iostream>
#include <string>

#include "se_defines.h"

SE_GLOBALS()

void read_random_str(char* ptr, ssize_t len) {
  std::ifstream urandom("/dev/urandom", std::ios::in | std::ios::binary);

  if (!urandom) {
    std::cerr << "Error opening /dev/urandom" << std::endl;
    exit(-1);
  }

  // Read 4 bytes of random data
  urandom.read(ptr, len);

  if (!urandom) {
    std::cerr << "Error reading from /dev/urandom" << std::endl;
    exit(-1);
  }

  // printable char
  for (int i = 0; i < len; i++) {
    if ((uint8_t)ptr[i] > 128) {
      ptr[i] -= 128;
    }
    ptr[i] = (ptr[i] % (126 - 32)) + 32;
  }

  // Close the file
  urandom.close();
}

char buf[1000];
char random_str[8];

void test_case(std::string content) {
  read_random_str(random_str, sizeof(random_str) - 1);
  char* ptr = random_str;

  snprintf(buf, sizeof(buf), content.c_str());

  if (!strcmp(buf, random_str)) {
    SE_TARGET_STATE(true);
  }
}

int main(int argc, char* argv[]) {
  std::istream* input;
  std::ifstream file;
  if (argc < 2) {
    input = &std::cin; // No file name provided, read from stdin
  } else {
    file.open(argv[1]);
    if (!file) {
      std::cerr << "Could not open the file.\n";
      return 1;
    }
    input = &file; // File opened successfully, read from file
  }
  std::string content(
      (std::istreambuf_iterator<char>(*input)),
      std::istreambuf_iterator<char>());
  test_case(content);
  return 0;
}
